const app = new Vue({
  el: '#mainapp',
  data() {
    return {
      tabnum: 0,
      isFirst: true,
      orderList: [],
      token: '',
      user: '',
      goodslist: '',
      showlist: '',
      listCount: 0,
      currentPage: 1,
      dialogFormVisible: false,
      dialogFormVisible2: false,
      categories: '',
      form: {
        id: '',
        name: '',
        category: '',
        img: '',
        s: '',
        n: '',
        l: '',
      },
      pswform: {
        passold: '',
        passnew: '',
        checkPassnew: '',
      },
      formLabelWidth: '120px',
      rules: {
        name: [
          {
            required: true,
            message: '请输入商品名',
            trigger: 'blur',
          },
        ],
        number: [
          {
            validator: this.checkNum,
            trigger: 'blur',
          },
        ],
        passold: [
          {
            validator: this.validatePass,
            require: true,
            message: '请输入密码',
            trigger: 'blur',
          },
        ],
        passnew: [{ validator: this.validatePass, trigger: 'blur' }],
        checkPassnew: [{ validator: this.validatePass2, trigger: 'blur' }],
      },
    }
  },
  computed: {
    getCategory() {
      return type => {
        let categoryName = ''
        switch (type) {
          case 1:
            categoryName = '汤粉面类'
            break
          case 2:
            categoryName = '小吃类'
            break
          case 3:
            categoryName = '饮料'
            break
          case 4:
            categoryName = '炖汤'
            break
          default:
            break
        }
        return categoryName
      }
    },
    getType() {
      return type => {
        let size = ''
        switch (type) {
          case 's':
            size = '小份'
            break
          case 'n':
            size = '正常'
            break
          case 'l':
            size = '大份'
            break
          default:
            break
        }
        return size
      }
    },
    getGoodsName() {
      return id => {
        const goods = this.goodslist.find(item => item.good_id === id)
        return goods.good_name
      }
    },
    showGoods(page = 1) {
      return page => {
        if (this.goodslist !== '') {
          return this.goodslist.filter(item => {
            return item.good_id <= page * 5 && item.good_id > (page - 1) * 5
          })
        }
        return ''
      }
    },
  },
  created() {
    this.init()
  },
  methods: {
    async upadetShow(num) {
      await this.$nextTick()
      this.showlist = this.showGoods(num)
    },
    async init() {
      //获取user基本信息并展示
      const { data } = await axios({
        method: 'get',
        url: '/users/getUser',
        headers: {
          Authorization: localStorage.getItem('token'),
        },
      })
      this.user = data
      this.getAllGoodList()
      this.getCategories()
      this.orderSSE()
    },
    /**
     * 开启订单SSE
     * 如果返回来的订单量不一致则改变数据并通知
     */
    orderSSE() {
      const source = new EventSource('/users/sse')
      source.onmessage = event => {
        const sseList = JSON.parse(event.data)
        if (this.orderList.length === 0 && sseList.length !== 0)
          this.orderList = sseList
        if (sseList.length > this.orderList.length) {
          this.orderList = sseList
          this.$notify.info({
            title: '您有新订单啦，请及时查看',
            duration: 0,
            offset: 100,
          })
        }
      }
    },
    logout() {
      //注销登出
      window.localStorage.removeItem('token')
      axios.get('/logout')
      location.href = '/login'
    },
    changePsw() {
      this.dialogFormVisible2 = true
    },

    switchTab(e, index) {
      //切换tab tabnum等于当前页面则return出去
      if (this.tabnum === index) return 0
      this.tabnum = index
      let nodeList = e.target.parentNode.parentNode.children
      for (let i = 0; i < nodeList.length; i++) {
        // if (this.isFirst && i === 1) {
        //   this.isFirst = false
        //   this.getOrderList()
        // }
        nodeList[i].classList.remove('actived')
        if (i === index) nodeList[i].classList.add('actived')
      }
    },

    async getOrderList() {
      try {
        const { data } = await axios({
          method: 'get',
          url: 'users/orders',
        })
        this.orderList = data.orders
      } catch (error) {
        console.log(error)
      }
    },
    async getAllGoodList() {
      const { data: res } = await axios({
        method: 'get',
        url: 'api/goods',
      })
      const jsonStr = JSON.stringify(res.goods)
      this.goodslist = JSON.parse(jsonStr)
      this.listCount = res.goodsCount
      this.upadetShow(this.currentPage)
    },
    async getCategories() {
      const { data } = await axios({
        method: 'get',
        url: 'api/categories',
      })
      this.categories = data.categories
    },

    addGood() {
      //添加商品
      this.dialogFormVisible = true
      this.$refs.dialogsSubumitBtn.onclick = () => {
        this.onAddGoodSubmit()
      }
    },
    async onAddGoodSubmit() {
      try {
        await axios({
          method: 'post',
          url: '/users/goods',
          data: {
            form: this.form,
          },
        })
        this.dialogFormVisible = false //隐藏
        //重新渲染
        this.getAllGoodList()
        this.upadetShow(this.currentPage)
      } catch (error) {
        alert(error)
      }
      this.dialogPassive()
    },

    async deleteGood(goodName) {
      //1. 删除安全检验
      //2. 数据库中删除
      //3. 页面数据删除
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            await axios({
              method: 'delete',
              url: '/users/goods',
              data: {
                good_name: goodName,
              },
            })
            // console.log(this.goodslist)
            // this.goodslist )
            this.goodslist = this.goodslist.filter(
              item => item.good_name !== goodName
            )
            this.listCount--
            this.$nextTick(() => this.upadetShow(this.currentPage))
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
          } catch (error) {}
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    /**
     * 删除订单
     */
    async deleteOrder(orderId) {
      this.$alert('你确定删除该订单吗，一旦删除不可恢复', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        callback: async action => {
          if (action === 'confirm') {
            try {
              await axios({
                method: 'delete',
                url: '/users/orders',
                data: {
                  orderId: orderId,
                },
              })
              await this.getOrderList()
            } catch (error) {}
          }
        },
      })
    },
    //获取商品信息
    resetForm(ref) {
      this.$refs[ref].resetFields()
    },

    updateGood(goods) {
      //获取当前信息
      this.form.id = goods.good_id
      this.form.name = goods.good_name
      this.form.img = goods.good_img
      this.form.s = goods.good_price.s
      this.form.n = goods.good_price.n
      this.form.l = goods.good_price.l
      this.form.category = goods.good_category
      this.dialogFormVisible = true
      this.$refs.dialogsSubumitBtn.onclick = () => {
        this.onUpdateGoodSubmit()
      }
    },
    // 提交更改商品信息
    async onUpdateGoodSubmit() {
      try {
        await axios({
          method: 'put',
          url: '/users/goods',
          data: {
            form: this.form,
          },
        })
        this.dialogFormVisible = false //隐藏
        this.$message({
          type: 'success',
          message: '更新成功!',
        })
        //重新渲染
        this.getAllGoodList()
        this.resetForm('goodsform') //重置form
      } catch (error) {
        console.log(error)
      }
    },

    handleCurrentChange() {
      this.upadetShow(this.currentPage)
    },
    dialogPassive() {
      this.dialogFormVisible = false
      this.resetForm('goodsform')
    },
    checkNum(rule, value, callback) {
      if (value === '') callback()
      if (typeof value !== 'number') callback(new Error('只允许空值和数字'))
    },
    validatePass(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.pswform.checkPass !== '') {
          this.$refs.pswform.validateField('checkPass')
        }
        callback()
      }
    },
    validatePass2(rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== this.pswform.passnew) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    },
    async submitForm(ref) {
      if (this.pswform.passnew === '') return 0
      if (this.pswform.passnew !== this.pswform.checkPassnew) {
        return 0
      }
      try {
        const res = await axios({
          method: 'post',
          url: '/users/changePsw',
          data: {
            psw: {
              oldpass: this.pswform.passold,
              passnew: this.pswform.passnew,
            },
          },
        })
        this.$alert('密码更改成功', '消息', {
          confirmButtonText: '确定',
          callback: this.logout(),
        })
      } catch (error) {
        console.log(error)
        this.$alert('密码更改失败，请查看旧密码是输入错误', '消息', {
          confirmButtonText: '确定',
        })
      }

      console.log(res.status)
    },
  },
})
